package ru.nsu.ccfit.kalah.activity;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import ru.nsu.ccfit.kalah.R;
import ru.nsu.ccfit.kalah.game.Score;

import java.util.List;

public class ScoresAdapter extends BaseAdapter {
    private List<Score> scores;
    private LayoutInflater inflater;
    private Context context;
    private static final int LAYOUT_ID = R.layout.activity_scores_list_item;

    public ScoresAdapter(Context context, List<Score> scores) {
        this.context = context;
        this.scores = scores;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return scores.size();
    }

    @Override
    public Object getItem(int i) {
        return scores.get(i);
    }

    @Override
    public long getItemId(int i) {
        return scores.get(i).getId();
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = inflater.inflate(LAYOUT_ID, null);
        }

        Score score = (Score) getItem(i);
        TextView firstPlayerName = (TextView) view.findViewById(R.id.first_player_name);
        firstPlayerName.setText(score.getFirstPlayer());
        TextView secondPlayerName = (TextView) view.findViewById(R.id.second_player_name);
        secondPlayerName.setText(score.getSecondPlayer());

        TextView firstPlayerScore = (TextView) view.findViewById(R.id.first_player_score);
        firstPlayerScore.setText(context.getString(R.string.activity_score_points_fmt, score.getFirstScore()));
        TextView secondPlayerScore = (TextView) view.findViewById(R.id.second_player_score);
        secondPlayerScore.setText(context.getString(R.string.activity_score_points_fmt, score.getSecondScore()));

        boolean isFirstLoser = score.getFirstScore() < score.getSecondScore();
        int cupId = isFirstLoser ? R.id.first_player_cup : R.id.second_player_cup;
        view.findViewById(R.id.first_player_cup).setVisibility(View.VISIBLE);
        view.findViewById(R.id.second_player_cup).setVisibility(View.VISIBLE);
        if (score.getFirstScore() != score.getSecondScore()) {
            view.findViewById(cupId).setVisibility(View.INVISIBLE);
        }

        return view;
    }
}
